package com.groupbuying.admin.service.impl;

import com.aliyun.openservices.shade.io.netty.util.internal.StringUtil;
import com.groupbuying.admin.connector.CheetahFeign;
import com.groupbuying.admin.connector.StoreFeign;
import com.groupbuying.admin.connector.SysconfigFeign;
import com.groupbuying.admin.constants.SysAgentInfoEnumConstants;
import com.groupbuying.admin.context.FilterContextHandler;
import com.groupbuying.admin.utils.PageUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.groupbuying.admin.constants.RedisKeyEnumConstants;
import com.groupbuying.admin.dao.UserRoleDao;
import com.groupbuying.admin.domain.UserDO;
import com.groupbuying.admin.service.UserService;
import com.groupbuying.admin.utils.AgentInfoCheckUtils;
import com.groupbuying.admin.utils.JsonUtils;
import com.groupbuying.admin.utils.MD5Utils;
import com.groupbuying.admin.utils.apiresult.AgentApiResultCode;
import com.groupbuying.admin.utils.apiresult.ApiResult;
import com.groupbuying.admin.utils.redis.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

import com.groupbuying.admin.dao.SysAgentInfoDao;
import com.groupbuying.admin.domain.SysAgentInfoDO;
import com.groupbuying.admin.service.SysAgentInfoService;



@Service
public class SysAgentInfoServiceImpl implements SysAgentInfoService {

	private static final Logger logger = LoggerFactory.getLogger(SysAgentInfoServiceImpl.class);

	@Autowired
    private SysconfigFeign sysconfigFeign;

	@Autowired
	private SysAgentInfoDao sysAgentInfoDao;

	@Autowired
	private UserService userService;

	@Autowired
	UserRoleDao userRoleMapper;

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private CheetahFeign cheetahFeign;
    @Autowired
	private StoreFeign storeFeign;

	@Override
	public SysAgentInfoDO get(String id){
		return sysAgentInfoDao.get(id);
	}

	@Override
	public SysAgentInfoDO getByAgentNo(String agentNo){return sysAgentInfoDao.getByAgentNo(agentNo); }

	@Override
	public SysAgentInfoDO getByAgentName(String agentName){return sysAgentInfoDao.getByAgentName(agentName); }
	
	@Override
	public List<SysAgentInfoDO> list(Map<String, Object> map){
		map.put("isDelete",SysAgentInfoEnumConstants.ENUM_ISDELETE_UNDEL);
        map.put("agentRel",map.get("agentId"));
		map.put("order", "desc");
		List<SysAgentInfoDO> sysAgentInfoList = sysAgentInfoDao.list(map);
		for (SysAgentInfoDO sysAgentInfo : sysAgentInfoList) {
			if(sysAgentInfo.getStatus().equals("00")){
				sysAgentInfo.setStatusName("停用");
			}else if(sysAgentInfo.getStatus().equals("01")){
				sysAgentInfo.setStatusName("正常");
			}else{
				sysAgentInfo.setStatusName("冻结");
			}
			String address = sysAgentInfo.getProvince() + " "+sysAgentInfo.getCity();
			sysAgentInfo.setAddress(address);
		}
		return sysAgentInfoList;
	}
	
	@Override
	public int count(Map<String, Object> map){
		return sysAgentInfoDao.count(map);
	}
	
	@Override
	public int save(SysAgentInfoDO sysAgentInfo){
		return sysAgentInfoDao.save(sysAgentInfo);
	}
	
	@Override
	public int update(SysAgentInfoDO sysAgentInfo){
		return sysAgentInfoDao.update(sysAgentInfo);
	}
	
	@Override
	public int remove(String id){
		return sysAgentInfoDao.remove(id);
	}
	
	@Override
	public int batchRemove(String[] ids){
		return sysAgentInfoDao.batchRemove(ids);
	}
	/**
	 * 更新一条数据
	 */
	@Override
	public int updateStatus(Map<String, Object> condMap) {
        /*获取token参数信息--代理商id*/
        String agentId = FilterContextHandler.getAgentId();
        condMap.put("id", agentId);
        if ((condMap.get("status").equals(SysAgentInfoEnumConstants.ENUM_STATUS_FROZEN))) {
            condMap.put("status", SysAgentInfoEnumConstants.ENUM_STATUS_FROZEN);
        } else if ((condMap.get("status").equals(SysAgentInfoEnumConstants.ENUM_STATUS_START))) {
            condMap.put("status", SysAgentInfoEnumConstants.ENUM_STATUS_START);
        } else {
            condMap.put("status", SysAgentInfoEnumConstants.ENUM_STATUS_STOP);
        }
        condMap.put("gmtModified", new Date());
        return this.sysAgentInfoDao.updateStatus(condMap);
    }

    /**
     * 注册代理商
     * @author cuich
     * @date 2019年7月26日11:03:05
     * @param sysAgentInfo
     * @return
     */
    @Override
	public ApiResult regist(SysAgentInfoDO sysAgentInfo) {
        String agentName;
        try{
            logger.error("SysAgentInfoServiceImpl-->regist start params:::"+ JsonUtils.objectToJson(sysAgentInfo));
            agentName = sysAgentInfo.getAgentName();
            //校验参数
            ApiResult checkAgentInfoResult = checkAgentInfo(sysAgentInfo);
            if(!AgentApiResultCode.SUCCESS.code().equals(checkAgentInfoResult.getCode())){
                logger.error("SysAgentInfoServiceImpl-->regist "+agentName+" checkAgentInfo fail "+JsonUtils.objectToJson(checkAgentInfoResult));
                return checkAgentInfoResult;
            }
			SysAgentInfoDO agentInfo = initAgentInfo(sysAgentInfo);
            if(null == agentInfo){
                return ApiResult.failure("代理商信息初始化失败");
            }
            //注册信息入库
            if(0 < save(agentInfo)){
                logger.error("SysAgentInfoServiceImpl-->regist "+agentName+" 将代理商用户数据同步到用户表");
                //同步数据到用户表
                ApiResult createUserResult = createUser(sysAgentInfo);
                if(!AgentApiResultCode.SUCCESS.code().equals(createUserResult.getCode())){
                    logger.error("SysAgentInfoServiceImpl-->regist "+agentName+" 同步用户表数据失败");
                    return createUserResult;
                }
            }else{
                logger.error("SysAgentInfoServiceImpl-->regist "+agentName+" 代理商数据落库失败");
                return ApiResult.failure(AgentApiResultCode.FAILURE_REGISTER.code(),AgentApiResultCode.FAILURE_REGISTER.message());
            }
        }catch(Exception e){
            agentName = sysAgentInfo.getAgentName();
            logger.error("SysAgentInfoServiceImpl-->regist "+agentName+" fail",e);
            return ApiResult.failure(AgentApiResultCode.OPRFAILURE.code(),AgentApiResultCode.OPRFAILURE.message());
        }

        logger.error("SysAgentInfoServiceImpl-->regist "+agentName+" success");
		return ApiResult.success(AgentApiResultCode.SUCCESS_REGISTER.code(),AgentApiResultCode.SUCCESS_REGISTER.message());
	}

    /**
     * 编辑代理商信息
     * @author cuich
     * @date 2019年7月30日15:53:39
     */
    @Override
    public ApiResult edit(SysAgentInfoDO sysAgentInfo) {
        String agentNo;
        agentNo =sysAgentInfo.getAgentNo();
        logger.error("SysAgentInfoServiceImpl-->edit params:::"+JsonUtils.objectToJson(sysAgentInfo));
        try{
            ApiResult checkResult = editCheckAgentInfo(sysAgentInfo);
            if(!ApiResult.success().getCode().equals(checkResult.getCode())){
                logger.error("SysAgentInfoServiceImpl-->edit "+agentNo+" fail "+checkResult.getMsg());
                return checkResult;
            }
			Map<String,Object> params =initEditParams(sysAgentInfo);
			logger.error("SysAgentInfoServiceImpl-->edit "+agentNo+" initEditParams result::: "+JsonUtils.objectToJson(params));
			if(MapUtils.isEmpty(params)){
				logger.error("SysAgentInfoServiceImpl-->edit "+agentNo+" fail 初始化参数失败");
				return ApiResult.failure(AgentApiResultCode.OPRFAILURE.code(),AgentApiResultCode.OPRFAILURE.message());
			}
			UserDO user = (UserDO)params.get("user");
			SysAgentInfoDO agentInfo = (SysAgentInfoDO) params.get("agentInfo");
			int count = update(agentInfo);
            int userCount = userService.update(user);
            if(count <= 0 || userCount <= 0){
                logger.error("SysAgentInfoServiceImpl-->edit "+agentNo+" fail 更新失败");
                return ApiResult.failure(AgentApiResultCode.OPRFAILURE.code(),AgentApiResultCode.OPRFAILURE.message());
            }
        }catch(Exception e){
            logger.error("SysAgentInfoServiceImpl-->edit "+agentNo+" fail ",e);
            return ApiResult.failure(AgentApiResultCode.OPRFAILURE.code(),AgentApiResultCode.OPRFAILURE.message());
        }
        logger.error("SysAgentInfoServiceImpl-->edit "+agentNo+" success");
        return ApiResult.success();
    }

	@Override
	public PageUtils agentFlowList(Map<String, Object> map) {
		PageUtils page=this.cheetahFeign.getagentMoneyFlows(map);
		return page;
	}

	/**
     * 同步代理商数据到用户数据表时创建用户数据
     * @author cuich
     * @date 2019年7月26日11:02:10
     * @param sysAgentInfo
     * @return
     */
	private ApiResult createUser(SysAgentInfoDO sysAgentInfo){
	    String agentNo = sysAgentInfo.getAgentNo();
		if(null != userService.getByUserName(agentNo)){
            logger.error("SysAgentInfoServiceImpl-->createUser "+agentNo+" 该用户已存在");
			return ApiResult.failure(AgentApiResultCode.FAILURE_NAMEEXIST.code(),AgentApiResultCode.FAILURE_NAMEEXIST.message());
		}
		UserDO user = initUser(sysAgentInfo);
		if(0 >= userService.save(user)){
            logger.error("SysAgentInfoServiceImpl-->createUser "+agentNo+" 同步数据到用户表失败");
			return ApiResult.failure(AgentApiResultCode.FAILURE_REGISTER.code(),AgentApiResultCode.FAILURE_REGISTER.message());
		}
		return ApiResult.success(AgentApiResultCode.SUCCESS_REGISTER.code(),AgentApiResultCode.SUCCESS_REGISTER.message());
	}

	private UserDO initUser(SysAgentInfoDO sysAgentInfo){
		UserDO user = new UserDO();
		user.setGmtCreate(new Date());
		user.setMobile(sysAgentInfo.getLeaderPhone());
		user.setPassword(sysAgentInfo.getPassword());
		user.setUsername(sysAgentInfo.getAgentNo());
		user.setName(sysAgentInfo.getLeaderName());
		List<Long> roles = new ArrayList<>();
		roles.add(SysAgentInfoEnumConstants.ENUM_ROLE_ID);
		user.setroleIds(roles);
		return user;
	}

    /**
     * 校验代理商请求参数
     * @author cuich
     * @date 2019年7月26日11:00:40
     */
	private ApiResult checkAgentInfo(SysAgentInfoDO agentInfo) {
	    String agentName = agentInfo.getAgentName();
	    String agentNo = agentInfo.getAgentNo();
        String redisKey = RedisKeyEnumConstants.ENUM_ADMIN_AGENT_REGIST + agentNo;
        if(redisUtils.isHasKey(redisKey)){
            logger.error("SysAgentInfoServiceImpl-->checkAgentInfo "+agentNo+" 重复请求 ");
            return ApiResult.failure(AgentApiResultCode.REAPEATREGIST.code(),AgentApiResultCode.REAPEATREGIST.message());
        }
		redisUtils.setKey(redisKey,agentInfo,180);
        
		if(null == agentInfo){
            logger.error("SysAgentInfoServiceImpl-->checkAgentInfo agentInfo为空");
			return ApiResult.failure(AgentApiResultCode.PARAMNULL.code(),AgentApiResultCode.PARAMNULL.message());
		}
		if(!AgentInfoCheckUtils.chackAgentParams(agentInfo)){
            logger.error("SysAgentInfoServiceImpl-->checkAgentInfo 请求参数为空");
            return ApiResult.failure(AgentApiResultCode.PARAMNULL.code(),AgentApiResultCode.PARAMNULL.message());
        }
        //判断代理商账号是否存在
        if(null != getByAgentNo(agentNo)){
            logger.error("SysAgentInfoServiceImpl-->regist checkAgentInfo.agentNo:"+agentNo+" agentNo is exist");
            return ApiResult.failure(AgentApiResultCode.FAILURE_AGENT_NO_EXIST.code(),AgentApiResultCode.FAILURE_AGENT_NO_EXIST.message());
        }
		//判断代理商名称是否存在
		if(null != getByAgentName(agentName)){
			logger.error("SysAgentInfoServiceImpl-->regist checkAgentInfo.agentNo:"+agentNo+" agentName is exist");
			return ApiResult.failure(AgentApiResultCode.FAILURE_AGENTNAMEEXIST.code(),AgentApiResultCode.FAILURE_AGENTNAMEEXIST.message());
		}
		//判断用户名是否存在
		if(null != userService.getByUserName(agentNo)){
			logger.error("SysAgentInfoServiceImpl-->regist checkAgentInfo.agentNo:"+agentNo+" userName is exist");
			return ApiResult.failure(AgentApiResultCode.FAILURE_USER_EXIST.code(),AgentApiResultCode.FAILURE_USER_EXIST.message());
		}
		//校验代理商名称中是否有特殊字符
		if(AgentInfoCheckUtils.checkAgentName(agentName) ||
				AgentInfoCheckUtils.checkAgentLeaderName(agentInfo.getLeaderName())){
            logger.error("SysAgentInfoServiceImpl-->checkAgentInfo "+agentName+" 代理商名字不合法，含特殊字符 ");
			return ApiResult.failure(AgentApiResultCode.FAILURE_LEADERNAMEFAIL.code(),AgentApiResultCode.FAILURE_LEADERNAMEFAIL.message());
		}
		//判断代理商账号是否有汉字
        if(AgentInfoCheckUtils.isHashChinese(agentNo) || AgentInfoCheckUtils.checkAgentLeaderName(agentNo)){
            logger.error("SysAgentInfoServiceImpl-->checkAgentInfo "+agentNo+" 代理商用户名不合法，含有汉字 ");
            return ApiResult.failure(AgentApiResultCode.FAILURE_NAMEHASCHINESE.code(),AgentApiResultCode.FAILURE_NAMEHASCHINESE.message());
        }
		//校验代理商手机号
		if(!AgentInfoCheckUtils.isMoblie(agentInfo.getLeaderPhone())){
            logger.error("SysAgentInfoServiceImpl-->checkAgentInfo "+agentNo+" 代理商手机号不合法 ");
			return ApiResult.failure(AgentApiResultCode.MOBILEFAIL.code(),AgentApiResultCode.MOBILEFAIL.message());
		}
		return ApiResult.success();
	}

	private ApiResult editCheckAgentInfo(SysAgentInfoDO agentInfo){
		String agentName = agentInfo.getAgentName();
		String agentNo = agentInfo.getAgentNo();
		if(null == agentInfo){
			logger.error("SysAgentInfoServiceImpl-->editCheckAgentInfo 请求参数为空");
			return ApiResult.failure(AgentApiResultCode.PARAMNULL.code(),AgentApiResultCode.PARAMNULL.message());
		}
		if(!AgentInfoCheckUtils.editChackAgentParams(agentInfo)){
			logger.error("SysAgentInfoServiceImpl-->editCheckAgentInfo 请求参数为空");
			return ApiResult.failure(AgentApiResultCode.PARAMNULL.code(),AgentApiResultCode.PARAMNULL.message());
		}
		//校验代理商名称中是否有特殊字符
		if(AgentInfoCheckUtils.checkAgentName(agentName) ||
				AgentInfoCheckUtils.checkAgentLeaderName(agentInfo.getLeaderName())){
			logger.error("SysAgentInfoServiceImpl-->editCheckAgentInfo "+agentName+" 代理商名字不合法，含特殊字符 ");
			return ApiResult.failure(AgentApiResultCode.FAILURE_LEADERNAMEFAIL.code(),AgentApiResultCode.FAILURE_LEADERNAMEFAIL.message());
		}
		//判断代理商账号是否有汉字
		if(AgentInfoCheckUtils.isHashChinese(agentNo) || AgentInfoCheckUtils.checkAgentLeaderName(agentNo)){
			logger.error("SysAgentInfoServiceImpl-->editCheckAgentInfo "+agentNo+" 代理商用户名不合法，含有汉字 ");
			return ApiResult.failure(AgentApiResultCode.FAILURE_NAMEHASCHINESE.code(),AgentApiResultCode.FAILURE_NAMEHASCHINESE.message());
		}
		//校验代理商手机号
		if(!AgentInfoCheckUtils.isMoblie(agentInfo.getLeaderPhone())){
			logger.error("SysAgentInfoServiceImpl-->editCheckAgentInfo "+agentNo+" 代理商手机号不合法 ");
			return ApiResult.failure(AgentApiResultCode.MOBILEFAIL.code(),AgentApiResultCode.MOBILEFAIL.message());
		}
		return ApiResult.success();
	}

	/**
	 * 初始化代理商信息
	 * @author cuich
	 * @date 2019年7月29日11:34:29
	 */
	private SysAgentInfoDO initAgentInfo(SysAgentInfoDO agentInfo){
		String agentName = agentInfo.getAgentName();
		try{
			String password = MD5Utils.encrypt(agentInfo.getAgentNo(), agentInfo.getPassword().trim());
			agentInfo.setPassword(password);
			String agentId =sysconfigFeign.getAgentId();
			logger.error("SysAgentInfoServiceImpl-->initAgentInfo agentId:"+agentId);
			agentInfo.setId(agentId);
			//本期插入都为1级
			agentInfo.setGrade("1");
			agentInfo.setStatus(SysAgentInfoEnumConstants.ENUM_STATUS_START);
			String parentAgentId = FilterContextHandler.getAgentId();
			if(!StringUtil.isNullOrEmpty(parentAgentId)){
                agentInfo.setAgentRel(parentAgentId);
            }
			agentInfo.setIsDelete(SysAgentInfoEnumConstants.ENUM_ISDELETE_UNDEL);
			agentInfo.setGmtCreate(new Date());
		}catch(Exception e){
			logger.error("SysAgentInfoServiceImpl-->initAgentInfo "+agentName+" 获取代理商ID失败",e);
			return null;
		}
		return agentInfo;
	}

	private Map<String,Object> initEditParams(SysAgentInfoDO sysAgentInfo){
		String agentNo = sysAgentInfo.getAgentNo();
		Map<String,Object> result = new HashMap();
		try{
			//获取原有代理商信息
			SysAgentInfoDO originalAgentInfo = get(sysAgentInfo.getId());
			if(null == originalAgentInfo){
				logger.error("SysAgentInfoServiceImpl-->initEditParams "+agentNo+" fail 获得原数据失败");
				return ApiResult.failure(AgentApiResultCode.FAILURE_USERUNEXIST.code(),AgentApiResultCode.FAILURE_USERUNEXIST.message());
			}
			String password = MD5Utils.encrypt(sysAgentInfo.getAgentNo(), sysAgentInfo.getPassword().trim());
			sysAgentInfo.setPassword(password);
			//获得用户user信息
			UserDO user = userService.getByUserName(agentNo);
			if(null == user){
				logger.error("SysAgentInfoServiceImpl-->initEditParams "+agentNo+" fail 获得用户表原数据失败");
				return ApiResult.failure(AgentApiResultCode.FAILURE_USERUNEXIST.code(),AgentApiResultCode.FAILURE_USERUNEXIST.message());
			}
			//判断输入的密码与数据库中密码是否一致
			if(!originalAgentInfo.getPassword().equals(sysAgentInfo.getPassword().trim())){
				//不一致才修改密码
				sysAgentInfo.setPassword(password);
				sysAgentInfo.setGmtModified(new Date());
				user.setPassword(password);
				user.setGmtModified(new Date());
			}
			result.put("user",user);
			result.put("agentInfo",sysAgentInfo);
		}catch(Exception e){
			logger.error("SysAgentInfoServiceImpl-->initEditParams "+agentNo+" fail",e);
			return null;
		}
		return result;
	}
	/**
	 * 通过代理商添加服务商
	 */
	@Override
	public ApiResult addAccount(Map<String, Object> map) {
		/*获取token参数信息--代理商id*/
		String agentId = FilterContextHandler.getAgentId();
		logger.info("SysAgentInfoServiceImpl.addAccount()------>agentId:"+agentId);
		map.put("agentId", agentId);
		return storeFeign.addAccount(map);
	}
	/**
	 * 通过代理商id获取服务商列表
	 */

	@Override
	public PageUtils getStoreAccountList(Map<String, Object> map) {
		/*从token获取代理商id*/
		String agentId = FilterContextHandler.getAgentId();
		logger.info("SysAgentInfoController.getStoreAccountList()----->获取到的代理商id为:"+agentId);
		if(agentId.equals(SysAgentInfoEnumConstants.ENUM_SUPER_AGENT)){
			map.put("providerType","0");
		}else{
			map.put("agentId", agentId);
			map.put("providerType", "0");
		}
		PageUtils sysAgentInfoList=storeFeign.getStoreAccountList(map);
		return sysAgentInfoList;
	}
	/**
	 * 通过代理商id获取服务门店商列表
	 */
	@Override
	public PageUtils storeMainInfoListByAgent(Map<String, Object> map) {
		/*从token获取代理商id*/
		String agentId = FilterContextHandler.getAgentId();
		logger.info("SysAgentInfoController.storeMainInfoListByAgent()----->获取到的代理商id为:"+agentId);
		map.put("id", agentId);
		map.put("providerType", "0");
		PageUtils storeMainInfoListByAgent=storeFeign.storeMainInfoListByAgent(map);
		return storeMainInfoListByAgent;
	}
	/**
	 * 通过代理商id获取门店运营人员列表
	 */
	@Override
	public PageUtils getStoreOperList(Map<String, Object> map) {
		/*从token获取代理商id*/
		String agentId = FilterContextHandler.getAgentId();
		logger.info("SysAgentInfoController.getStoreOperList()----->获取到的代理商id为:"+agentId);
		map.put("id", agentId);
		map.put("providerType", "0");
		PageUtils getStoreOperList=storeFeign.getStoreOperList(map);
		return getStoreOperList;
	}
	/**
	 * 更改store中心数据
	 */
	@Override
	public ApiResult updateStoreStatus(Map<String, Object> map) {
		/*从token获取代理商id*/
		logger.info("SysAgentInfoController-->updateStoreStatus() params:::"+JsonUtils.objectToJson(map));
		ApiResult result = storeFeign.updateStatus(map);
		logger.info("SysAgentInfoController-->updateStoreStatus() result:::"+JsonUtils.objectToJson(result));
		return result;
	}
}
